import React, { useState, useRef, useEffect, useContext } from 'react';
import { LoadingOutlined, EditOutlined, DeleteOutlined, KeyOutlined, } from '@ant-design/icons';
import { message, Table, Button, Space, Input, Modal, Form, Select, } from 'antd';
import axios from 'axios';
import Draggable from 'react-draggable';
import { useNavigate } from 'react-router-dom';
import { AuthContext } from '../../contexts/AuthContext';
import './index.css'
import { useTranslation } from 'react-i18next';

const { Search } = Input;
const { Option } = Select;
const layout = {
    labelCol: {
        span: 8,
    },
    wrapperCol: {
        span: 16,
    },
};

const ProjectList = (refreshKey) => {
    const { t } = useTranslation();
    const [open, setOpen] = useState(false);
    const [confirmLoading, setConfirmLoading] = useState(false);
    const [disabled, setDisabled] = useState(true);
    const [bounds, setBounds] = useState({ left: 0, top: 0, bottom: 0, right: 0 });
    const [currentRow, setCurrentRow] = useState(null);
    const [loading, setLoading] = useState(false);
    const navigate = useNavigate();
    const [generateLoading, setGenerateLoading] = useState(false);
    const [currentGeneratingKey, setCurrentGeneratingKey] = useState(null);
    const draggleRef = useRef(null);
    const [searchValue, setSearchValue] = useState('');
    const [tableData, setTableData] = useState([]); // 初始化为数组
    const [messageApi, contextHolder] = message.useMessage();
    const [allData, setAllData] = useState([]);
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
        total: 0
    });
    const { token, username } = useContext(AuthContext);
    const hasFetchedRef = useRef(false);
    useEffect(() => {
        if (!hasFetchedRef.current) {
            if (username && token) {
                hasFetchedRef.current = true;
                fetchPackages(pagination.current, pagination.pageSize);
            }
        }
    }, [token, refreshKey]);
    const fetchPackages = async () => {
        setLoading(true);
        const params = {};
        try {
            const res = await axios.post('/api/v1/pkg/query', params,
                {
                    headers: {
                        'Authorization': token
                    }
                }
            );
            if (res.data.code === 0) {
                const responseData = res.data?.data || [];
                const dataArray = Array.isArray(responseData) ? responseData : [responseData];

                const formattedData = dataArray.map((item, index) => ({
                    key: item.didid || `temp-${item.pkgFilename}-${index}`,
                    originalName: item.pkgFilename,
                    name: item.pkgName || t('未命名'),
                    address: item.download_url || t('无地址'),
                    identity: item.didid || ''
                }));
                setAllData(formattedData);
                setTableData(formattedData);
                setPagination(prev => ({
                    ...prev,
                    total: formattedData.length
                }));
            } else if (res.data.code === 1003 & res.data.code === 1006) {
                message.error(t('Token失效，请重新登录'))
                localStorage.removeItem('username');
                localStorage.removeItem('enc_token');
                localStorage.removeItem('privilege_level');
                navigate('/login');
            }
        } catch (error) {
            console.error('获取数据失败:', error);
        } finally {
            setLoading(false);
        }
    };
    const handleTableChange = (newPagination) => {
        const { current, pageSize } = newPagination;
        const startIndex = (current - 1) * pageSize;
        const endIndex = startIndex + pageSize;
        const currentPageData = allData.slice(startIndex, endIndex);

        setTableData(currentPageData);
        setPagination({
            ...newPagination,
            total: allData.length
        });
    };
    const filteredData = React.useMemo(() => {
        if (!searchValue) return allData;
        return allData.filter(item =>
            item.name.toLowerCase().includes(searchValue.toLowerCase())
        );
    }, [allData, searchValue]);

    const onSearch = (value) => {
        setSearchValue(value);
        setPagination(prev => ({
            ...prev,
            current: 1
        }));
    };
    const columns = [
        {
            title: t('项目名'),
            dataIndex: 'name',
            key: 'name',
            fixed: 'left',
            render: (text, record) => (
                <a
                    href={`/project/detail/${record.originalName}`}
                    onClick={(e) => {
                        e.preventDefault();
                        if (!record.identity) {
                            message.warning(t('该项目尚未生成身份标识'));
                            return;
                        }
                        navigate(`/project/detail/${record.originalName}`, {
                            state: {
                                pkg_file_url: record.address //传递文件地址
                            }
                        });
                    }}
                >
                    {text}
                </a>
            )
        },
        {
            title: t('文件储存地址'),
            dataIndex: 'address',
            key: 'address',
            render: (text) => text ? <a href={text} target="_blank" rel="noopener noreferrer">{text}</a> : '无地址'
        },
        {
            title: t('身份标识'),
            dataIndex: 'identity',
            key: 'identity',
            render: (text) => text || t('未生成')
        },
        {
            title: t('生成身份标识'),
            key: 'generate',
            render: (_, record) => (
                <Button
                    type="link"
                    icon={generateLoading && record.key === currentGeneratingKey ? <LoadingOutlined /> : <KeyOutlined />}
                    onClick={() => {
                        setCurrentGeneratingKey(record.key);
                        handleGenerateIdentity(record.key);
                    }}
                    disabled={record.identity !== '' || generateLoading}
                    className='identity-button'
                >
                    {generateLoading && record.key === currentGeneratingKey ? t('生成中...') : t('生成')}
                </Button>
            ),
        },
        {
            title: t('删除身份标识'),
            key: 'delete',
            render: (_, record) => (
                <Button
                    danger
                    type="link"
                    icon={<DeleteOutlined />}
                    onClick={() => handleDeleteIdentity(record.key)}
                    disabled={!record.identity}
                    className='identity-button'
                >
                    {t('删除')}
                </Button>
            ),
        },
        {
            title: t('更新did文档'),
            key: 'update',
            render: (_, record) => (
                <>
                    <Button
                        type="link"
                        icon={<EditOutlined />}
                        onClick={() => handleUpdateClick(record)}
                        disabled={!record.identity}
                        className='identity-button'
                    >
                        {t('更新')}
                    </Button></>
            ),
        },
    ];
    // 生成身份标识
    const handleGenerateIdentity = async (key) => {
        const row = tableData.find(item => item.key === key);
        const address = row.address;
        const name = address.split('/').pop();
        setGenerateLoading(true);
        try {
            const response = await axios.post('/api/v1/did/create_identity', { name });

            if (response.data.code === 0) {
                setTableData(prevData =>
                    prevData.map(item =>
                        item.key === key
                            ? { ...item, identity: response.data.data.DidID }
                            : item
                    )
                );
                message.success(t('身份标识已生成'));
                setTimeout(() => {
                    window.location.reload();
                }, 1000);
            } else if (res.data.code === 1003 & res.data.code === 1006) {
                message.error(t('Token失效，请重新登录'))
                localStorage.removeItem('username');
                localStorage.removeItem('enc_token');
                localStorage.removeItem('privilege_level');
                navigate('/login');
            } else {
                message.error(response.data.msg);
            }
        } catch (error) {
            message.error(t('生成身份标识失败'));
        } finally {
            setCurrentGeneratingKey(null);
            setGenerateLoading(false);
        }
    };
    // 更新
    const handleUpdateClick = (record) => {
        setCurrentRow(record);
        setOpen(true);
    };
    // 删除
    const handleDeleteIdentity = async (key) => {
        // setTableData(prevData =>
        //     prevData.map(item =>
        //         item.key === key ? {...item, identity: ''} : item
        //     )
        // );
        const formData = new FormData()
        formData.append('didID', key)
        const response = await axios.delete("/api/v1/did/remove_identity", {
            headers: {
                'Content-Type': 'multipart/form-data'
            },
            data: formData
        })
        if (response.data.code === 200) {
            message.success(t('身份标识已删除'))
            setTimeout(() => {
                window.location.reload();
            }, 1000);
        } else {
            message.error(t('删除失败'))
        }
    };
    const ModalTitle = () => (
        <div
            style={{ width: '100%', cursor: 'move' }}
            onMouseOver={() => {
                setDisabled(false);
            }}
            onMouseOut={() => {
                setDisabled(true);
            }}
            onFocus={() => {
            }}
            onBlur={() => {
            }}
        >
            {t('更新did文档')}
        </div>
    );
    const [form] = Form.useForm();

    const handleOk = async () => {
        setConfirmLoading(true);
        const newAddress = form.getFieldValue('address')
        const newType = form.getFieldValue('type')
        const newService = [{
            id: currentRow?.key,
            serviceEndpoint: newAddress,
            type: newType
        }];
        try {
            console.log(currentRow?.key)
            const queryResponse = await axios.get('/api/v1/did/query_identity', {
                params: {
                    did: currentRow?.key
                }
            })
            const originDocument = queryResponse.data.data.document
            originDocument.service = newService
            const response = await axios.put('/api/v1/did/update_document', originDocument)
            if (response.data.code === 200) {
                message.success(t('更新成功'));
                setOpen(false);
                setTimeout(() => {
                    window.location.reload();
                }, 1000);
            } else if (response.data.code === 1003 & response.data.code === 1006) {
                message.error(t('Token失效，请重新登录'))
                localStorage.removeItem('username');
                localStorage.removeItem('enc_token');
                localStorage.removeItem('privilege_level');
                navigate('/login');
            }
        } catch (error) {
            message.error(t('更新失败'));
        } finally {
            setConfirmLoading(false);
        }
    };
    const onStart = (_event, uiData) => {
        const { clientWidth, clientHeight } = window.document.documentElement;
        const targetRect = draggleRef.current?.getBoundingClientRect();

        if (!targetRect) return;

        setBounds({
            left: -targetRect.left + uiData.x,
            right: clientWidth - (targetRect.right - uiData.x),
            top: -targetRect.top + uiData.y,
            bottom: clientHeight - (targetRect.bottom - uiData.y),
        });
    };

    return (
        <>
            {contextHolder}
            <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
                <Space.Compact>
                    <Search
                        style={{ marginTop: '40px' }}
                        placeholder={t("输入项目名搜索")}
                        onSearch={onSearch}
                        onChange={(e) => setSearchValue(e.target.value)}
                        value={searchValue}
                        enterButton
                        allowClear
                    />
                </Space.Compact>
            </div>
            <div className="table-container" style={{ width: '100%' }}>
                <Table
                    columns={columns}
                    dataSource={filteredData}
                    rowKey="key"
                    scroll={{ x: 'max-content' }}
                    pagination={{
                        current: pagination.current,
                        pageSize: pagination.pageSize,
                        total: pagination.total,
                        showSizeChanger: true,
                        pageSizeOptions: ['10', '20', '50'],
                        showTotal: (total, range) => `${range[0]}-${range[1]} of ${total} ${t('条')}`
                    }}
                    onChange={handleTableChange}
                    loading={loading}
                />
            </div>
            <Modal
                className="custom-modal"
                title={<ModalTitle />}
                open={open}
                onOk={handleOk}
                confirmLoading={confirmLoading}
                onCancel={() => setOpen(false)}
                modalRender={(modal) => (
                    <Draggable
                        disabled={disabled}
                        bounds={bounds}
                        nodeRef={draggleRef}
                        onStart={onStart}
                    >
                        <div ref={draggleRef}>{modal}</div>
                    </Draggable>
                )}
            >
                <p className='formname'>{t("正在更新:")} {currentRow?.name || ''}</p>
                <Form
                    {...layout}
                    form={form}
                    name="control-hooks"
                    style={{
                        maxWidth: 600,
                    }}
                >
                    <Form.Item
                        name="address"
                        label={t('更新文档储存地址')}
                        rules={[
                            {
                                required: true,
                            },
                        ]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item
                        name="type"
                        label={t('文档类型')}
                    >
                        <Select
                            placeholder={t('请选择')}
                            allowClear
                        >
                            <Option value="html">html</Option>
                            <Option value="md">md</Option>
                            <Option value="pdf">pdf</Option>
                            <Option value="word">word</Option>
                        </Select>
                    </Form.Item>
                </Form>
            </Modal></>
    );
};

export default ProjectList;
